package com.gongyou.forum.controller;

import com.gongyou.common.constant.UserConstant;
import com.gongyou.common.entity.Result;
import com.gongyou.common.pojo.User;
import com.gongyou.common.utils.JwtUtil;
import com.gongyou.forum.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author LiQuanPing
 * @Date 2021-03-19 15:14
 * @Version 1.8
 * @creed: ♂♂Talk is cheap,show me the code♀♀
 * <p>
 * 用户登陆,注册,忘记密码 处理controller
 */
@Slf4j
@RestController
@RequestMapping("/userLogin")
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;

    //用户手机号码登录
    @RequestMapping("/login")
    public Result userLogin(@RequestBody User user) {
        log.info("电话是" + user.getPhone() + ";密码是" + user.getPassword());
        String phone = user.getPhone();
        User user1 = userLoginService.login(user);
        if (user1 != null) {
            boolean checkpw = BCrypt.checkpw(user.getPassword(), user1.getPassword());
            if (checkpw) {
                //密码匹配成功
                String jwt = JwtUtil.createJWT(phone, phone, null);
                Map map =  new HashMap();
                map.put("userId",user1.getId());
                map.put("phone",user1.getPhone());
                map.put("gender",user1.getGender());
                map.put("avatarUrl",user1.getAvatarUrl());
                map.put("username",user1.getNickName());
                map.put("token",jwt);
                return new Result(true, UserConstant.USER_LOGIN_FULL, map);
            }else {
                return new Result(false, UserConstant.USER_NAME_ERROR);
            }
        } else {
            return new Result(false, UserConstant.USER_NAME_ERROR);
        }

    }

    //用户手机号码登录
    @RequestMapping("/register")
    public Result register(@RequestBody User user) {
        //System.out.println("电话是"+user.getPhone()+";密码是"+user.getPassword());
  /*      String phone = user.getPhone();
        boolean flag = userLoginService.register(user);
        if (flag) {
            return new Result(true, "注册成功");
        } else {
            return new Result(false, "注册失败");
        }*/
        return null;
    }
}
